<template>
	<view v-if="loading === false" class="container">
		<view v-if="!cartList.length" class="empty-contaner">
			<view class="upload-btn" @click="showPopup = true">
				<image src="@/static/icon/img/add.png" mode="aspectFit"></image>
				<text>点击上传</text>
			</view>
			<view class="tips">
				请上传需要打印得文件
			</view>
		</view>
		<view v-else class="content-contaner">
			<view class="delete-all" @click="changeDelete">
				{{isDeleting ? '取消删除' : '批量删除'}}
			</view>
			<view class="content">
				<view class="ctn-item" v-for="item in cartList" :key="item.id">
					<radio style="transform: scale(0.8);" :checked="isDeleting ? item.isDelete : item.selected === 1"
						color="#FF9C24" border-color="#CECECE" @click="selectGoods(item)" />
					<image class="ctn-item-center" :src="item.original_img" mode="aspectFit" />
					<view class="ctn-item-right">
						<view class="item-info">
							<view class="item-name">
								<text class="oneline-hide">{{item.goods_name}}</text>
								<view v-if="!isDeleting" class="delete" @click="handleDelete(item.id)">
									<image src="@/static/img/delete.png" mode="aspectFit">
								</view>
								<view v-else class="delete" />
							</view>
							<view class="item-desc oneline-hide">
								{{item.doc_remark}}
							</view>
						</view>
						<view class="item-detail">
							<view class="price">
								<span>￥</span>{{item.goods_price}}
							</view>
							<NumberBox :value="item.goods_num" @change="_changeGoodsDetail(item, $event)" />
						</view>
						<view v-if="item.type === 1" class="item-action">
							<view class="preview" @click="handlePreview(item.doc_json)">
								预览
							</view>
							<view class="print-setting" @click.stop="$navTo('pages/indexs/doc/setting', {id: item.id})">
								打印设置
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="footer">
				<radio style="transform: scale(0.8);" :checked="selectAll.selectAll" color="#FF9C24" borderColor="#727272"
					@click="handleSelectAll" />
				<text class="select-all" @click="handleSelectAll">全选</text>
				<block v-if="!isDeleting">
					<view class="footer-ctn">
						<view class="txt">
							合计：<span class="icon">￥</span><span class="price">{{selectAllPrice}}</span>
						</view>
						<view class="txt">
							含6元运费，满15元包邮
						</view>
					</view>
					<view class="submit-btn" @click="handleSubmit">
						立即支付({{selectAll.selectNum}})
					</view>
				</block>
				<view v-else class="submit-btn" style="margin-left: auto;" @click="handleDelete">
					删除
				</view>
			</view>
		</view>
		<view v-if="cartList.length" class="add-file-btn" @touchend="showPopup = true" @mouseup="showPopup = true">
			<u-icon name="plus" color="#fff" size="50"></u-icon>
		</view>
		<UploadFile v-model="showPopup" type="file" @upload="handleUpload" />
	</view>
</template>

<script>
	import UploadFile from '../components/UploadFile.vue'
	import NumberBox from '../components/NumberBox.vue'
	import {
		PrintApi
	} from '@/api'
	import {
		debounce,
		isArray,
		previewFile,
		uploadFile
	} from '@/utils/util'
	import {
		PYTHON_URL
	} from '@/config/request'
	export default {
		components: {
			UploadFile,
			NumberBox
		},
		data() {
			return {
				showPopup: false,
				loading: true,
				isDeleting: false, // 正在删除
				cartList: [],
				selectAllPrice: 0, // 选中商品总价
			}
		},
		onLoad() {
			uni.$on('UploadFileEvent', this.handleLocalUpload)
		},
		onShow() {
			this.getCartList()
		},
		onUnload() {
			uni.$off('UploadFileEvent')
		},
		computed: {
			selectAll() {
				let data = {
					selectNum: 0,
					selectAll: false
				}
				if (!this.cartList.length)
					return data
				this.cartList.forEach(item => {
					if (this.isDeleting ? item.isDelete : item.selected)
						return data.selectNum += 1
				})
				if (this.cartList.length === data.selectNum) data.selectAll = true
				return data
			},
		},
		methods: {
			// 处理本地文件上传
			async handleLocalUpload(file) {
				try {
					this.$nextTick(() => this.$showLoading({
						title: '解析中'
					}))
					const pageData = await PrintApi.getFilePage(file.url)
					let form = {
						type: 1,
						file: PYTHON_URL + '/' + file.url,
						pageRange: `1-${pageData.result.page}`,
						maxPage: pageData.result.page, // 最大页数
						goods_name: file.name
					}
					if (pageData.result.index_image) form.index_image = pageData.result.index_image
					await PrintApi.AjaxJionCart(form)
					await this.getCartList()
					uni.hideLoading()
				} catch (err) {
					uni.hideLoading()
					this.$showToast(err || '上传失败')
				}
			},
			handlePreview(data) {
				if (!data)
					return this.$showToast('预览失败')
				previewFile(JSON.parse(data).data[0].file)
			},
			// 获取购物车
			getCartList() {
				// this.$showLoading()
				return PrintApi.getCartList()
					.then((res) => {
						this.cartList = res.result
						this.selectAllPrice = res.allprice
						if (!this.cartList.length) {
							// 清空状态
							this.showPopup = true
							this.isDeleting = false
							this.selectAllPrice = 0
						} else {
							this.showPopup = false
						}
					})
					.catch(err => {
						if (err.message == '购物车暂无商品') this.$showToast(err.message)
					})
					.finally(() => {
						console.log('getCartList finally');
						this.loading = false
						// uni.hideLoading()
					})
			},
			/**
			 * 更改商品信息
			 */
			_changeGoodsDetail(data, status) {
				this.$showLoading()
				const {
					value: goods_num,
					selected
				} = status
				const param = {
					rec_id: data.id,
					is_select: typeof selected === 'number' ? selected : data.selected,
					goods_number: goods_num || data.goods_num
				}
				PrintApi.CartChangeInfo(param)
					.then(res => {
						// 更新数据
						this.selectAllPrice = res.allprice
						data.goods_num = param.goods_number
						data.selected = param.is_select
						if (res.doc_remark) data.doc_remark = res.doc_remark
					})
					.catch(err => {
						console.log(err);
						uni.hideLoading()
						this.$showToast(err?.msg || err)
					})
					.finally(() => uni.hideLoading())
			},
			/**
			 * 选中商品
			 */
			selectGoods(data) {
				if (this.isDeleting) {
					// 删除模式
					this.$set(data, 'isDelete', data.isDelete === 1 ? 0 : 1)
				} else {
					// 选中模式
					this._changeGoodsDetail(data, {
						selected: data.selected === 1 ? 0 : 1
					})
				}
			},
			/**
			 * 全选
			 */
			handleSelectAll() {
				if (this.isDeleting) {
					this.cartList = this.cartList.map(item => {
						return {
							...item,
							isDelete: this.selectAll.selectAll ? false : true
						}
					})
				} else {
					this.$showLoading()
					PrintApi.CartChangeAll({
							is_select: this.selectAll.selectAll ? 0 : 1
						})
						.then(() => {
							this.getCartList()
						})
						.catch(err => this.$showToast(err.msg || err.message))
						.finally(() => uni.hideLoading())
				}
			},
			/** 
			 * 上传文件
			 */
			async handleUpload(e) {
				try {
					this.$showLoading({
						title: '上传并解析中'
					})
					for (const item of e.fileList) {
						const files = await uploadFile(item)
						const pageData = await PrintApi.getFilePage(files.result.url)
						let form = {
							type: 1,
							file: PYTHON_URL + '/' + files.result.url,
							pageRange: `1-${pageData.result.page}`,
							maxPage: pageData.result.page, // 最大页数
							goods_name: item.name,
						}
						if (pageData.result.index_image) form.index_image = pageData.result.index_image
						await PrintApi.AjaxJionCart(form)
					}
					this.showPopup = false
					await this.getCartList()
					if (e.errNum) this.$showToast(`${e.errNum}个文件上传失败`)
				} catch (err) {
					this.$showToast(err.message)
				} finally {
					uni.hideLoading()
				}
			},
			/** 
			 * 立即支付
			 */
			handleSubmit() {
				if (!this.cartList.length) {
					return this.$showToast('当前购物车暂无商品')
				}
				if (!this.selectAll.selectNum) {
					return this.$showToast('请先选择商品')
				}
				this.$navTo('pages/indexs/doc/payment')
			},
			changeDelete() {
				if (!this.isDeleting) {
					this.isDeleting = true
				} else {
					this.isDeleting = false
				}
			},
			/**
			 * 删除
			 * @param {Number} id 指定删除的索引
			 */
			handleDelete(id = null) {
				if (!this.cartList.length) {
					return this.$showToast('当前购物车暂无商品')
				}
				if (!this.selectAll.selectNum) {
					return this.$showToast('请先选择商品')
				}
				this.$showLoading()
				let delListIndexs = []
				if (typeof id === 'number') {
					// 独立删除
					delListIndexs = [id]
				} else {
					// 批量删除
					this.cartList.forEach((item) => {
						if (item.isDelete) delListIndexs.push(item.id)
					})
				}
				PrintApi.CartDelete({
						ids: delListIndexs.join(',')
					})
					.then(res => {
						this.getCartList()
					})
					.catch(err => this.$showToast(err.message || err.errMsg))
					.finally(() => uni.hideLoading())
			},
		}
	}
</script>

<style lang="scss">
	page {
		background: $theme-bg-color;
	}
</style>
<style lang="scss" scoped>
	.container {
		--footer-height: 110rpx;
	}

	// 空
	.empty-contaner {
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
		width: 100vw;
		height: 100vh;
	}

	.upload-btn {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 18rpx 76rpx;
		border-radius: 5rpx;
		background: linear-gradient(135deg, #ffb300 0%, #ff8400 100%);
		box-shadow: 0 0 10rpx 0 #ffbb0099;

		>image {
			width: 26rpx;
			height: 26rpx;
		}

		>text {
			margin-left: 10rpx;
			color: #ffffff;
			font-size: 24rpx;
		}
	}

	.tips {
		margin-top: 30rpx;
		text-align: center;
		color: #989898;
		font-size: 24rpx;
	}

	// 列表
	.content-contaner {
		padding: 20rpx;
		padding-bottom: calc(constant(safe-area-inset-bottom) + 110rpx);
		padding-bottom: calc(env(safe-area-inset-bottom) + 110rpx);
	}

	.delete-all {
		margin-left: auto;
		width: 156rpx;
		height: 54rpx;
		line-height: 54rpx;
		border-radius: 10rpx;
		border: 2rpx solid $theme-color;
		background: #f9f9f9;
		color: $theme-color;
		font-size: 24rpx;
		text-align: center;
	}

	.content {
		margin-top: 20rpx;
	}

	.ctn-item {
		display: flex;
		align-items: flex-start;
		margin-bottom: 30rpx;
		padding: 30rpx;
		padding-right: 0;
		border-radius: 10rpx;
		box-shadow: 0 16rpx 40rpx 0 #00000008;
		background-color: #fff;
	}

	.ctn-item-center {
		margin-left: 20rpx;
		margin-right: 10rpx;
		width: 66rpx;
		height: 44rpx;
	}

	.ctn-item-center02 {
		margin-left: 20rpx;
		width: 280rpx;
	}

	.ctn-item-right {
		flex: 1;
		margin-left: auto;
	}

	.item-info {
		padding-right: 30rpx;
	}

	.item-name {
		display: flex;
		align-items: center;
		justify-content: space-between;

		>text {
			max-width: 480rpx;
			color: #000000;
			font-size: 28rpx;
		}

		.delete {
			position: relative;
			width: 40rpx;
			height: 40rpx;

			>image {
				width: 100%;
				height: 100%;
			}

			&::after {
				content: '';
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
				width: 60rpx;
				height: 60rpx;
				background-color: transparent;
			}
		}
	}

	.item-desc {
		margin-top: 10rpx;
		color: #989898;
		font-size: 20rpx;
	}

	.item-detail {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 20rpx;
		padding-right: 30rpx;

		>.price {
			display: flex;
			align-items: flex-end;
			color: #ff2e2e;
			font-size: 36rpx;

			>span {
				font-size: 28rpx;
			}
		}
	}

	.item-action {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		margin-top: 30rpx;
		padding: 30rpx;
		padding-bottom: 0;
		height: 54rpx;
		line-height: 54rpx;
		border-top: 2rpx solid #f3f3f3;
		background: #ffffff;
		font-size: 24rpx;
	}

	.preview {
		width: 108rpx;
		border-radius: 10rpx;
		border: 2rpx solid #a8a8a8;
		color: #a8a8a8;
		text-align: center;
	}

	.print-setting {
		margin-left: 20rpx;
		width: 156rpx;
		border-radius: 10rpx;
		border: 2rpx solid $theme-color;
		color: $theme-color;
		text-align: center;
	}

	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		padding-bottom: $safe-btm-constant;
		padding-bottom: $safe-btm-env;
		// height: 110rpx;
		height: var(--footer-height);
		border-top: 2rpx solid #f4f4f4;
		background-color: #fff;
		z-index: 999;
	}

	.select-all {
		color: #727272;
		font-size: 26rpx;
	}

	.footer-ctn {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: flex-end;

		>.txt {
			color: #b5b5b5;
			font-size: 20rpx;

			>span {
				color: $theme-color;
			}

			>.icon {
				font-size: 24rpx;
			}

			>.price {
				font-size: 36rpx;
			}
		}
	}

	.submit-btn {
		margin-left: 20rpx;
		width: 228rpx;
		height: 70rpx;
		line-height: 70rpx;
		border-radius: 35rpx;
		background: linear-gradient(135deg, #ffb300 4%, #ff6a00 100%);
		color: #ffffff;
		text-align: center;
		font-size: 24rpx;
		background-color: #fff;
	}

	// 添加按钮
	.add-file-btn {
		position: fixed;
		right: 70rpx;
		bottom: calc(var(--footer-height) + constant(safe-area-inset-bottom) + 200rpx);
		bottom: calc(var(--footer-height) + env(safe-area-inset-bottom) + 200rpx);
		display: flex;
		justify-content: center;
		align-items: center;
		width: 120rpx;
		height: 120rpx;
		border-radius: 50%;
		background: $gradient-bg-color;
		box-shadow: 0 0 10rpx 5rpx rgba(0, 0, 0, 0.2);
		transition: all 0.2s ease;
		z-index: 99;

		&:active {
			transform: scale(1.1);
			filter: brightness(80%);
		}
	}
</style>